<template>
    <div>
        <div class="ccui-navigation">
            <el-button
                size="mini"
                type="primary-icon-medium"
                icon="icon-ccui-return"
                @click="handleBack"
            >返回
            </el-button
            >
            <div class="ccui-navigation-divider"/>
            <!-- 面包屑 -->
            <el-breadcrumb
                class="ccui-navigation-crumbs-container"
                separator-class="el-icon-arrow-right"
            >
                <el-breadcrumb-item
                    :to="{ path: $store.getters.getBreadcrumb('level1').path }"
                >{{ $store.getters.getBreadcrumb("level1").name }}
                </el-breadcrumb-item
                >
                <el-breadcrumb-item
                    :to="{
            path: '/inventoryManagement/storeManagement/storeManagementList',
          }"
                >库存管理
                </el-breadcrumb-item
                >
                <el-breadcrumb-item
                    :to="{
            path: '/inventoryManagement/writeOff/ListAll',
          }"
                >财务出库管理
                </el-breadcrumb-item
                >
                <el-breadcrumb-item
                    :to="{
            path: '/inventoryManagement/writeOff/ListAll',
          }"
                >财务出库
                </el-breadcrumb-item
                >
                <el-breadcrumb-item>
          <span class="ccui-curr-crumb ccui-ml-10">
            {{ titleName }}
          </span>
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="ccui-app-container-detail">
            <div class="ccui-app-container-detail-body">
                <el-tabs v-model="activeName" class="el-tabs__customize">
                    <!-- 基本信息 -->
                    <el-tab-pane label="基本信息" name="first">
                        <keep-alive>
                            <basicInformation
                                :exwarehouseCountSum="exwarehouseCountSum"
                                :exwarehouseMoneySum="exwarehouseMoneySum"
                                :categoryName="categoryName"
                                :categoryCode="categoryCode"
                                @warehouseId="handleWarehouseId"
                                @changeTianbaodanwei="HandleChangeTianbaodanwei"
                                @changCangku="handleChangCangku"
                                ref="basicInformation"
                                @isValid="isValid"
                                :basicInformation="basicInformation"
                            >
                            </basicInformation>
                        </keep-alive>
                    </el-tab-pane>
                    <!-- 采购清单 -->
                    <el-tab-pane label="采购清单" name="two">
                        <keep-alive>
                            <purchaseList
                                :purchaseList="purchaseList"
                                @exwarehouseCountSum="handleExwarehouseCountSum"
                                @exwarehouseMoneySum="handleExwarehouseMoneySum"
                                @categoryName="handleCategoryName"
                                @categoryCode="handleCategoryCode"
                                :warehouseId="warehouseId"
                                ref="purchaseList"
                            >
                            </purchaseList>
                        </keep-alive>
                    </el-tab-pane>
                    <!-- 成本明细 -->
                    <el-tab-pane label="成本明细" name="three">
                        <costDetailTable ref="costDetailTable"/>
                    </el-tab-pane>
                    <!-- 合同附件 -->
                    <el-tab-pane label="附件" name="four" v-if="isTrue" class="file-group">
                        <keep-alive>
                            <fileInfo ref="fileInfo" v-model="fileList"></fileInfo>
                        </keep-alive>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>
        <!--  按钮  -->
        <el-bottom-guide>
            <ul class="ccui-bottom-button">
                <li>
                    <el-button
                        type="bottom"
                        icon="icon-ccui-save"
                        @click="handleZhanCun()"
                    >暂存
                    </el-button
                    >
                </li>
                <li>
                    <el-button type="bottom" icon="icon-ccui-save" @click="handleSubmit()"
                    >保存并校验
                    </el-button
                    >
                </li>
                <li>
                    <el-button
                        type="bottom"
                        icon="icon-ccui-save-submit"
                        @click="handleReset()"
                    >保存并提交
                    </el-button
                    >
                </li>
                <li>
                    <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
                    >返回
                    </el-button
                    >
                </li>
            </ul>
        </el-bottom-guide>
    </div>
</template>
<script>
import basicInformation from "../components/basicInformation";
import fileInfo from "@/basa/components/public/uploadInfo2";
import purchaseList from "../components/purchaseList";
import costDetailTable from "@/app/financial/financialWriteOff/financialWriteOffAdd/components/costDetailTable";
import {
    getDataAdd,
    getDataDetails,
    getDataZhanCun,
    getDataEditor,
} from "../api";

export default {
    name: "Add",
    data() {
        return {
            activeName: "first",
            titleName: "",
            basicInformation: {},//基本信息
            purchaseList: [],//清单
            fileList: [],//附件
            exwarehouseCountSum: "", //出库数量和
            exwarehouseMoneySum: "", //出库金额和
            categoryName: "", //分类名称
            categoryCode: "",//分类code
            warehouseId: "", //仓库id
            judgeValue: true,
            isValidSuccess: "", //valide验证基本信息必填项
            changeTianbaodanwei: 2, //1更换2没更换
            changCangku: 2, //1更换2没更换
            isTrue: false
        };
    },
    components: {
        basicInformation,
        fileInfo,
        purchaseList,
        costDetailTable
    },
    mounted() {
        if (this.$route.query.ifAdd == 2) {//2编辑1新增
            let id = this.$route.query.id; //出库单id
            getDataDetails({id: id}).then((res) => {
                if (res.data.code == 0) {
                    this.basicInformation = res.data.data.exwarehouseBO;
                    this.titleName =
                        "编辑 " + res.data.data.exwarehouseBO.exwarehouseName;
                    if (this.basicInformation.exwarehouseCount) {
                        Number(this.basicInformation.exwarehouseCount).toFixed(3);
                    }
                    if (this.basicInformation.exwarehouseMoney) {
                        Number(this.basicInformation.exwarehouseMoney).toFixed(2);
                    }
                    this.purchaseList = res.data.data.exwarehouseBOList;
                    if (this.purchaseList.length > 0) {
                        this.purchaseList.forEach((item) => {
                            if (item.storageCount || item.storageCount === 0) {
                                item.storageCount = Number(item.storageCount).toFixed(
                                    3
                                );
                            }
                            if (item.unStockCount || item.unStockCount === 0) {
                                item.unStockCount = Number(item.unStockCount).toFixed(
                                    3
                                );
                            }
                            if (item.exwarehouseCount || item.exwarehouseCount === 0) {
                                item.exwarehouseCount = Number(item.exwarehouseCount).toFixed(
                                    3
                                );
                            }
                            if (item.exwarehouseMoney || item.exwarehouseMoney === 0) {
                                item.exwarehouseMoney = Number(item.exwarehouseMoney).toFixed(
                                    2
                                );
                            }
                            if (item.availableStockCount || item.availableStockCount === 0) {
                                item.availableStockCount = Number(
                                    item.availableStockCount
                                ).toFixed(3);
                            }
                            if (item.unitPriceWithTax || item.unitPriceWithTax === 0) {
                                item.unitPriceWithTax = Number(item.unitPriceWithTax).toFixed(
                                    2
                                );
                            }
                        });
                    }
                    
                    this.fileList = res.data.data.exwarehouseFiles;
                    this.fileList.forEach(item => {
                        item.createTime = item.uploadTime;
                        item.uploadId = item.fileInfoId;
                        item.fileSize = Math.floor(item.fileSize / 1024) + "kb"
                    });
                    this.isTrue = true;
                }
            });
        } else {
            this.isTrue = true;
            this.titleName = "新增财务出库";
        }
    },
    methods: {
        //清空清单-->切换填报单位
        HandleChangeTianbaodanwei(data) {
            this.changeTianbaodanwei = data;
            if (this.changeTianbaodanwei != this.changCangku) {
                this.$refs.purchaseList.tableData = [];
            } else if (this.changeTianbaodanwei == 1 && this.changCangku == 1) {
                this.$refs.purchaseList.tableData = [];
            } else {//恢复数据
                this.$refs.purchaseList.tableData = JSON.parse(
                    JSON.stringify(this.$refs.purchaseList.tableDataClone)
                );
            }
        },
        //清空清单-->切换仓库
        handleChangCangku(data) {
            this.changCangku = data;
            if (this.changeTianbaodanwei != this.changCangku) {
                this.$refs.purchaseList.tableData = [];
            } else if (this.changeTianbaodanwei == 1 && this.changCangku == 1) {
                this.$refs.purchaseList.tableData = [];
            } else {//恢复数据
                this.$refs.purchaseList.tableData = JSON.parse(
                    JSON.stringify(this.$refs.purchaseList.tableDataClone)
                );
            }
        },
        //返回
        handleBack() {
            this.$router.go(-1);
        },
        //出库数量
        handleExwarehouseCountSum(data) {
            this.exwarehouseCountSum = data;
        },
        //出库金额
        handleExwarehouseMoneySum(data) {
            this.exwarehouseMoneySum = data;
        },
        //仓库id
        handleWarehouseId(data) {
            this.warehouseId = data;
        },
        //分类名称
        handleCategoryName(data) {
            this.categoryName = data;
        },
        //分类code
        handleCategoryCode(data) {
            this.categoryCode = data
        },
        //验证基本信息必填项
        isValid(val) {
            this.isValidSuccess = val;
        },
        //保存
        handleSubmit() {
            this.judgeValue = true;
            this.getDataAdd(0);
        },
        //提交
        handleReset() {
            this.judgeValue = true;
            this.getDataAdd(1);
        },
        //暂存
        handleZhanCun() {
            this.judgeValue = true;
            this.getDataZhanCun();
        },
        getDataAdd(operType) {
            //调用组件
            this.$refs.basicInformation.validateBaseinfo();
            let smpExwarehouse = this.$refs.basicInformation.form;
            let smpExwarehouseList = this.$refs.purchaseList.tableData;
            let smpExwarehouseCostBO = this.$refs["costDetailTable"].tableData.length? this.$refs["costDetailTable"].tableData[0] : {};
            
            if (smpExwarehouseList.length > 0) {
                smpExwarehouseList.forEach((item, index) => {
                    item.sn = index //排序号
                    if (index === 0) {
                        if (item.storageType || item.storageType === 0) {
                            smpExwarehouse.exwarehouseType = item.storageType;
                        } else {
                            smpExwarehouse.exwarehouseType = item.exwarehouseType;
                        }
                    }
                    if (item.storageType || item.storageType === 0) {
                        item.exwarehouseType = item.storageType;
                    }
                    if (this.judgeValue) {
                        if (item.isOtherCost == 0 && item.isServices == 0) {
                            if (item.exwarehouseCount === 0 || item.exwarehouseCount === "0") {
                                this.judgeValue = false;
                                this.$message({
                                    message: "批次号为" + item.batchNumber + "的物资，出库数量不能为0",
                                    type: "error",
                                    showClose: true,
                                    ccuiCustom: true,
                                    duration: 8000
                                });
                            }
                        }
                    }
                    if (this.judgeValue) {
                        if (item.isOtherCost == 0 && item.isServices == 0) {
                            if (item.exwarehouseCount === "" || item.exwarehouseCount === undefined) {
                                this.judgeValue = false;
                                this.$message({
                                    message: "批次号为" + item.batchNumber + "的物资，出库数量不能为空",
                                    type: "error",
                                    showClose: true,
                                    ccuiCustom: true,
                                    duration: 8000
                                });
                            }
                        }
                    }
                    if (this.judgeValue) {
                        if (item.isOtherCost == 0 && item.isServices == 0) {
                            if (Number(item.unStockCount) < Number(item.exwarehouseCount)) {
                                this.judgeValue = false;
                                this.$message({
                                    message: "批次号为" + item.batchNumber + "的物资，可用库存数量" + item.unStockCount + "，出库数量不得大于可用库存数量",
                                    type: "error",
                                    showClose: true,
                                    ccuiCustom: true
                                });
                            }
                        }
                    }
                });
            } else {
                this.judgeValue = false;
                this.$message({
                    message: "采购清单不得为空",
                    type: "error",
                    showClose: true,
                    ccuiCustom: true,
                    duration: 8000
                });
            }
            
            let fileList = JSON.parse(JSON.stringify(this.fileList))
            if (fileList.length > 0) {
                fileList.forEach((item, index) => {
                    item.sn = Number(index) + 1;
                    if (item.fileInfoId) {
                        item.uploadId = item.fileInfoId;
                        delete item.fileInfoId;
                    }
                    if (item.createTime) {
                        item.uploadTime = new Date(item.createTime.replace(/-/g, "/")).getTime();
                    }
                    if (item.fileName) {
                        delete item.fileName;
                    }
                    if (item.fileSize) {
                        delete item.fileSize;
                    }
                });
            }
            
            let param = {
                operType: operType,
                smpExwarehouse: smpExwarehouse,
                smpExwarehouseList: smpExwarehouseList,
                smpExwarehouseCostBO: smpExwarehouseCostBO,
                uploadIds: fileList,
                isShowPageLoading: true
                
            };
            if (this.isValidSuccess) {
                if (this.judgeValue) {
                    if (this.$route.query.ifAdd == 1) {
                        getDataAdd(param).then((res) => {
                            if (res.data.code == 0) {
                                if (operType === 0) {
                                    this.$message({
                                        message: "保存并校验成功",
                                        type: "success",
                                        showClose: true,
                                        ccuiCustom: true
                                    });
                                } else {
                                    this.$message({
                                        message: "保存并提交成功",
                                        type: "success",
                                        showClose: true,
                                        ccuiCustom: true
                                    });
                                }
                                if (this.$route.query.all == 1) {
                                    this.$router.push({
                                        path: "/inventoryManagement/writeOff/ListAll",
                                    });
                                } else {
                                    if (operType === 0) {
                                        this.$router.push({
                                            path: "/inventoryManagement/writeOff/ListSubmit",
                                        });
                                    } else {
                                        this.$router.push({
                                            path: "/inventoryManagement/writeOff/ListApproval",
                                        });
                                    }
                                }
                            }
                        });
                    } else {
                        getDataEditor(param).then((res) => {
                            if (res.data.code == 0) {
                                if (operType === 0) {
                                    this.$message({
                                        message: "保存并校验成功",
                                        type: "success",
                                        showClose: true,
                                        ccuiCustom: true
                                    });
                                } else {
                                    this.$message({
                                        message: "保存并提交成功",
                                        type: "success",
                                        showClose: true,
                                        ccuiCustom: true
                                    });
                                }
                                if (this.$route.query.all == 1) {
                                    this.$router.push({
                                        path: "/inventoryManagement/writeOff/ListAll",
                                    });
                                } else if (this.$route.query.turn == 1) {
                                    this.$router.push({
                                        path: "/inventoryManagement/writeOff/ListApprovalTurn",
                                    });
                                } else {
                                    if (operType === 0) {
                                        this.$router.push({
                                            path: "/inventoryManagement/writeOff/ListSubmit",
                                        });
                                    } else {
                                        this.$router.push({
                                            path: "/inventoryManagement/writeOff/ListApproval",
                                        });
                                    }
                                }
                            }
                        });
                    }
                }
            } else {
                this.activeName = "first";
            }
        },
        getDataZhanCun() {
            let smpExwarehouse = this.$refs.basicInformation.form;
            let smpExwarehouseList = this.$refs.purchaseList.tableData;
            let smpExwarehouseCostBO = this.$refs["costDetailTable"].tableData.length? this.$refs["costDetailTable"].tableData[0] : {};
            if (smpExwarehouseList.length > 0) {
                smpExwarehouseList.forEach((item, index) => {
                    item.sn = index //排序号
                    if (index === 0) {
                        if (item.storageType || item.storageType === 0) {
                            smpExwarehouse.exwarehouseType = item.storageType;
                        } else {
                            smpExwarehouse.exwarehouseType = item.exwarehouseType;
                        }
                    }
                    if (item.storageType || item.storageType === 0) {
                        item.exwarehouseType = item.storageType;
                    }
                    if (!item.exwarehouseCount) {
                        item.exwarehouseCount = null
                    }
                    if (Number(item.unStockCount) < Number(item.exwarehouseCount)) {
                        this.judgeValue = false;
                        this.$message({
                            message: "批次号为" + item.batchNumber + "的物资，可用库存数量" + item.unStockCount + "，出库数量不得大于可用库存数量",
                            type: "error",
                            showClose: true,
                            ccuiCustom: true
                        });
                    }
                });
            }
            let fileList = JSON.parse(JSON.stringify(this.fileList))
            if (fileList.length > 0) {
                fileList.forEach((item, index) => {
                    item.sn = Number(index) + 1;
                    if (item.fileInfoId) {
                        item.uploadId = item.fileInfoId;
                        delete item.fileInfoId;
                    }
                    if (item.createTime) {
                        item.uploadTime = new Date(item.createTime.replace(/-/g, "/")).getTime();
                    }
                    if (item.fileName) {
                        delete item.fileName;
                    }
                    if (item.fileSize) {
                        delete item.fileSize;
                    }
                });
            }
            let param = {
                smpExwarehouse: smpExwarehouse,
                smpExwarehouseList: smpExwarehouseList,
                smpExwarehouseCostBO: smpExwarehouseCostBO,
                uploadIds: fileList,
                isShowPageLoading: true
            };
            if (this.judgeValue) {
                getDataZhanCun(param).then((res) => {
                    if (res.data.code == 0) {
                        this.$message({
                            message: "暂存成功",
                            type: "success",
                            showClose: true,
                            ccuiCustom: true
                        });
                        if (this.$route.query.all == 1) {
                            this.$router.push({
                                path: "/inventoryManagement/writeOff/ListAll",
                            });
                        } else if (this.$route.query.turn == 1) {
                            this.$router.push({
                                path: "/inventoryManagement/writeOff/ListApprovalTurn",
                            });
                        } else {
                            this.$router.push({
                                path: "/inventoryManagement/writeOff/ListSubmit",
                            });
                        }
                    }
                });
            }
        }
    },
};
</script>
<style lang="scss" scoped>
/deep/ .file-group .el-group-title .group-content {
    margin-top: 40px;
}

/deep/ .file-group {
    margin-top: 10px;
}
</style>

